import websocket
import threading
import json

class Socket:

    def __init__(self, framework):
        self.framework = framework
        self.socket = None
        self.socket_task = threading.Thread(name="task", target=self.task)
        self.socket_task.daemon = True
        self.socket_task.start()

    def task(self):
        websocket.enableTrace(False)
        self.socket = websocket.WebSocketApp("ws://127.0.0.1:8181", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
        self.socket.on_open = self.on_open
        self.socket.run_forever()

    def on_open(self, ws):
        self.write({"type": "robot_status", "data": "success"})

    def on_message(self, ws, message):
        print(self, ws, message)

    def write(self, message):
        if self.socket is not None:
            self.socket.send(json.dumps(message))

    def log(self, data):
        if self.socket is not None:
            self.socket.send(json.dumps({"type": "debug", "content": data}))

    def on_error(self, ws, error):
        self.socket = None

    def on_close(self, ws):
        self.socket = None
